/*
 * WeatherSession.cpp
 *
 *  Created on: Apr 13, 2010
 *      Author: songyp
 */

#include "WeatherSession.h"
#include "WeatherProtocol.h"

#include <WeatherAndCity.h>

_LIT(KWeatherServer, "WeatherServer");

TInt StartServer();

EXPORT_C RWeatherSession::RWeatherSession()
	{
	
	}

EXPORT_C TInt RWeatherSession::Connect()
	{
	TInt err = CreateSession( KWeatherServer, TVersion(1, 0, 0) );
	if( err != KErrNone )
		{
		StartServer();
		err = CreateSession( KWeatherServer, TVersion(1, 0, 0) );
		}
	return err;
	}

EXPORT_C TInt RWeatherSession::GetWeather( TInt aCity )
	{
	TInt weather = -1;
	TPckg<TInt> data( weather );
	TIpcArgs args( aCity, &data );
	TInt err = SendReceive( EGetWeather, args );
	return weather;
	}

TInt StartServer()
{
	RProcess server;
    server.Create ( KWeatherServer, KNullDesC );

    TRequestStatus status;
    server.Rendezvous(status);

    if ( status != KRequestPending )
    {
		server.Kill(0);
		server.Close();
		return KErrGeneral;
    }
    else 
    {
		server.Resume();
    }

    User::WaitForRequest(status);
 
    if ( status != KErrNone )
    {
    	server.Close();
		return status.Int();
    }

    return KErrNone;
}
